package com.ruoyi.course.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.course.domain.CdStudentTopic;
import com.ruoyi.course.enums.TopicStatusEnum;
import com.ruoyi.course.service.ICdStudentTopicService;
import com.ruoyi.course.utils.RoleUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.course.domain.CdTopicMessage;
import com.ruoyi.course.service.ICdTopicMessageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 题目信息Controller
 *
 * @author ruoyi
 * @date 2023-12-18
 */
@RestController
@RequestMapping("/topic/topic")
public class CdTopicMessageController extends BaseController {
    @Autowired
    private ICdTopicMessageService cdTopicMessageService;

    @Autowired
    private RoleUtils roleUtils;

    @Autowired
    private ICdStudentTopicService cdStudentTopicService;

    /**
     * 查询题目信息列表
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:list')")
    @GetMapping("/list")
    public TableDataInfo list(CdTopicMessage cdTopicMessage) {
        startPage();
        List<CdTopicMessage> list = cdTopicMessageService.selectCdTopicMessageList(cdTopicMessage);
        return getDataTable(list);
    }

    /**
     * 查询题目信息列表-不分页
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:list')")
    @GetMapping("/listAll")
    public AjaxResult listAll(CdTopicMessage cdTopicMessage) {
        // 学生只能查看自己选择的课题，教师只能查看自己创建的课题
        // 系主任可查看所有
        if (roleUtils.isStudent() && !roleUtils.isTeacher() && !roleUtils.isDirector()) {
            // 学生：通过子表查主表
            List<CdStudentTopic> cdStudentTopicList = cdStudentTopicService.selectCdStudentTopicByStudentId(SecurityUtils.getUserId());
            List<CdTopicMessage> list = new ArrayList<>();
            for (CdStudentTopic cdStudentTopic : cdStudentTopicList) {
                CdTopicMessage topicMessage = cdTopicMessageService.selectCdTopicMessageByTopicId(cdStudentTopic.getTopicId());
                list.add(topicMessage);
            }
            return AjaxResult.success(list);
        } else if (roleUtils.isTeacher()) {
            // 教师：与正常逻辑相比，加一个筛选条件
            cdTopicMessage.setTeacherId(SecurityUtils.getUserId());
        }
        List<CdTopicMessage> list = cdTopicMessageService.selectCdTopicMessageList(cdTopicMessage);
        return AjaxResult.success(list);
    }

    /**
     * 导出题目信息列表
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:export')")
    @Log(title = "题目信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CdTopicMessage cdTopicMessage) {
        List<CdTopicMessage> list = cdTopicMessageService.selectCdTopicMessageList(cdTopicMessage);
        ExcelUtil<CdTopicMessage> util = new ExcelUtil<CdTopicMessage>(CdTopicMessage.class);
        util.exportExcel(response, list, "题目信息数据");
    }

    /**
     * 获取题目信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:query')")
    @GetMapping(value = "/{topicId}")
    public AjaxResult getInfo(@PathVariable("topicId") Long topicId) {
        return success(cdTopicMessageService.selectCdTopicMessageByTopicId(topicId));
    }

    /**
     * 新增题目信息
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:add')")
    @Log(title = "题目信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CdTopicMessage cdTopicMessage) {
        return toAjax(cdTopicMessageService.insertCdTopicMessage(cdTopicMessage));
    }

    /**
     * 修改题目信息--指导教师修改草稿状态
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:edit')")
    @Log(title = "题目信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CdTopicMessage cdTopicMessage) {
        // 指导教师随时修改题目，不限制状态
        return toAjax(cdTopicMessageService.updateCdTopicMessage(cdTopicMessage));
    }

    /**
     * 提交题目
     *
     * @param topicIds
     * @return
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:edit')")
    @PutMapping("/submit/{topicIds}")
    public AjaxResult submit(@PathVariable Long[] topicIds) {
        int success = 0;
        int error = 0;
        for (Long topicId : topicIds) {
            CdTopicMessage cdTopicMessage = new CdTopicMessage();
            cdTopicMessage.setTopicId(topicId);
            cdTopicMessage.setStatus(TopicStatusEnum.TOPIC_AUDIT.getStatus());
            // 状态改成待审核状态，且之前的状态必须为草稿状态
            int result = cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_DRAFT.getStatus());
            if (result > 0) success++;
            else error++;
        }

        return AjaxResult.success("提交成功：" + success + "提交失败：" + error);
    }

    /**
     * 审核通过
     *
     * @param topicIds
     * @return
     */
    @PutMapping("/pass/{topicIds}")
    @PreAuthorize("@ss.hasPermi('topic:topic:trail')")
    public AjaxResult pass(@PathVariable Long[] topicIds) {
        int success = 0;
        int error = 0;
        for (Long topicId : topicIds) {
            CdTopicMessage cdTopicMessage = new CdTopicMessage();
            cdTopicMessage.setTopicId(topicId);
            cdTopicMessage.setStatus(TopicStatusEnum.TOPIC_APPROVED.getStatus());
            // 状态改成通过状态，且之前的状态必须为待审核状态
            int result = cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_AUDIT.getStatus());
            if (result > 0) success++;
            else error++;
        }

        return AjaxResult.success("操作成功：" + success + "操作失败：" + error);
    }

    /**
     * 审核不通过
     *
     * @param topicIds
     * @return
     */
    @PutMapping("/fail/{topicIds}")
    @PreAuthorize("@ss.hasPermi('topic:topic:trail')")
    public AjaxResult fail(@PathVariable Long[] topicIds) {
        int success = 0;
        int error = 0;
        for (Long topicId : topicIds) {
            CdTopicMessage cdTopicMessage = new CdTopicMessage();
            cdTopicMessage.setTopicId(topicId);
            cdTopicMessage.setStatus(TopicStatusEnum.TOPIC_DRAFT.getStatus());
            // 状态退回为草稿状态，且之前的状态必须为待审核状态
            int result = cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_AUDIT.getStatus());
            if (result > 0) success++;
            else error++;
        }

        return AjaxResult.success("退回成功：" + success + "退回失败：" + error);
    }

    /**
     * 学生选题
     *
     * @param topicId
     * @return
     */
    @PutMapping("/chooseTopic/{topicId}")
    @PreAuthorize("@ss.hasPermi('topic:topic:choose')")
    public AjaxResult chooseTopic(@PathVariable Long topicId) {
        if (!roleUtils.isStudent()) {
            // 如果不是学生
            return AjaxResult.error("你不是学生，不能选题");
        }

        List<CdStudentTopic> studentTopicList = cdStudentTopicService.selectCdStudentTopicByTopicId(topicId);
        for (CdStudentTopic studentTopic : studentTopicList) {
            if (SecurityUtils.getUserId().equals(studentTopic.getStudentId())) {
                // 如果这个学生已经选了这个课题
                return AjaxResult.error("你已选择了此题，不能重复选择");
            }
        }

        CdTopicMessage cdTopicMessage = cdTopicMessageService.selectCdTopicMessageByTopicId(topicId);
        if (cdTopicMessage.getMaxNum() != null && studentTopicList.size() >= cdTopicMessage.getMaxNum()) {
            return AjaxResult.error("此题选择人数已满，不能再选");
        }

        CdStudentTopic cdStudentTopic = new CdStudentTopic();
        cdStudentTopic.setTopicId(topicId);
        cdStudentTopic.setStudentId(SecurityUtils.getUserId());
        cdStudentTopicService.insertCdStudentTopic(cdStudentTopic);

        return AjaxResult.success("选题成功");
    }

    /**
     * 指导教师正式开始题目
     * @param topicId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:start')")
    @PutMapping("/start/{topicId}")
    public AjaxResult start(@PathVariable Long topicId) {
        List<CdStudentTopic> list = cdStudentTopicService.selectCdStudentTopicByTopicId(topicId);
        if (list.isEmpty()) {
            return AjaxResult.error("此题目没人选择，无法开始");
        }

        CdTopicMessage cdTopicMessage = new CdTopicMessage();
        cdTopicMessage.setTopicId(topicId);
        cdTopicMessage.setStatus(TopicStatusEnum.TOPIC_START.getStatus());
        // 题目状态改为正式开始，确保当前状态为学院通过状态
        int result = cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_APPROVED.getStatus());
        if (result > 0) return AjaxResult.success("操作成功");
        else return AjaxResult.error("请确保此题目为学院审核通过状态");
    }

    /**
     * 学生提交材料
     * @param cdTopicMessage
     * @return
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:stuSubmit')")
    @PutMapping("/stuSubmit")
    public AjaxResult stuSubmit(@RequestBody CdTopicMessage cdTopicMessage) {
        // 学生提交材料，需要保证题目是正式开始状态
        return toAjax(cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_START.getStatus()));
    }

    /**
     * 学生预约检查
     * @param topicId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:appoint')")
    @PutMapping("/appoint/{topicId}")
    public AjaxResult appoint(@PathVariable Long topicId) {
        CdTopicMessage topicMessage = cdTopicMessageService.selectCdTopicMessageByTopicId(topicId);
        Date checkStartTime = topicMessage.getCheckStartTime();
        Date checkEndTime = topicMessage.getCheckEndTime();
        if (checkStartTime != null && checkEndTime != null && DateUtils.getNowDate().compareTo(checkStartTime) > 0 && DateUtils.getNowDate().compareTo(checkEndTime) < 0) {
            CdTopicMessage cdTopicMessage = new CdTopicMessage();
            cdTopicMessage.setTopicId(topicId);
            cdTopicMessage.setStatus(TopicStatusEnum.TOPIC_APPOINTING.getStatus());
            // 学生预约检查，必须保证之前是开始状态
            int result = cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_START.getStatus());
            if (result > 0) return AjaxResult.success("预约成功");
            else return AjaxResult.error("预约失败");
        }

        return AjaxResult.error("不在预约时间范围内，无法预约");

    }

    /**
     * 教师同意检查
     * @param topicId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:edit')")
    @PutMapping("/accept/{topicId}")
    public AjaxResult accept(@PathVariable Long topicId) {
        CdTopicMessage cdTopicMessage = new CdTopicMessage();
        cdTopicMessage.setTopicId(topicId);
        cdTopicMessage.setStatus(TopicStatusEnum.TOPIC_APPOINTED.getStatus());
        // 教师同意检查，必须保证之前是已预约状态
        int result = cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_APPOINTING.getStatus());
        if (result > 0) return AjaxResult.success("操作成功");
        else return AjaxResult.error("操作失败");
    }

    /**
     * 教师拒绝检查
     * @param topicId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:edit')")
    @PutMapping("/reject/{topicId}")
    public AjaxResult reject(@PathVariable Long topicId) {
        CdTopicMessage cdTopicMessage = new CdTopicMessage();
        cdTopicMessage.setTopicId(topicId);
        cdTopicMessage.setStatus(TopicStatusEnum.TOPIC_START.getStatus());
        // 教师拒绝检查，必须保证之前是已预约状态(退回到开始状态)
        int result = cdTopicMessageService.updateCdTopicMessage(cdTopicMessage, TopicStatusEnum.TOPIC_APPOINTING.getStatus());
        if (result > 0) return AjaxResult.success("操作成功");
        else return AjaxResult.error("操作失败");
    }

    /**
     * 删除题目信息
     */
    @PreAuthorize("@ss.hasPermi('topic:topic:remove')")
    @Log(title = "题目信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{topicIds}")
    public AjaxResult remove(@PathVariable Long[] topicIds) {
        return toAjax(cdTopicMessageService.deleteCdTopicMessageByTopicIds(topicIds));
    }
}
